package com.briup.srms.base.web.controller;

import com.jacky.base.utils.Message;
import com.jacky.base.utils.MessageUtil;
import com.briup.srms.base.bean.BaseFile;
import com.briup.srms.base.service.IBaseFileService;
import com.jacky.base.utils.FastDFS;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

/**
 * @program: paz
 * @description: 文件控制器类
 * @author: jacky
 * @create: 2019-03-15 23:15
 **/
@Api(description = "文件上传相关接口")
@RestController
@RequestMapping("/file")
public class FileController {
	@Autowired
	private IBaseFileService baseFileService;
	
	private void downLoadFromUrl(String urlStr, OutputStream os) {
        try {
        	URL url = null;
        	HttpURLConnection conn = null;
        	InputStream inputStream = null;
            try {
            	url = new URL(urlStr);
                conn = (HttpURLConnection) url.openConnection();
                // 设置超时间为3秒
                conn.setConnectTimeout(3 * 1000);
                // 防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                // 得到输入流
                inputStream = conn.getInputStream();
                // 获取自己数组
                byte[] getData = readInputStream(inputStream);
                // 将读取到的流写入到输出流中
                os.write(getData);
                os.flush();
			} finally {
				if(inputStream != null) {
					inputStream.close();
				}
				if(os != null) {
					os.close();
				}
			}
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

	@ApiOperation(value = "下载文件", produces = "application/octet-stream")
	@GetMapping("download")
	public void download(HttpServletResponse response,String url) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("Content-Type", "application/octet-stream");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(url, "utf-8"));
		OutputStream os = response.getOutputStream();
		downLoadFromUrl(url, os);
	}
	
    @ApiOperation(value="远程文件删除")
    @GetMapping("deleteById")
    public Message delete(
            @ApiParam(value = "文件id",required = true) String id
    ) throws Exception {
    	// 删除附件服务器上的文件
        int code = FastDFS.delete(id);
        if(code == 0) {
        	// 删除数据库中的记录
            baseFileService.deleteById(id);
            return MessageUtil.success("删除成功");
        } else {
            return MessageUtil.error("删除失败");
        }
    }


    @ApiOperation(value="文件上传",notes="文件大小限制为3M, 上传完成后需要保存图片id与groupid，通过http://121.199.29.84/8888/group1/fileId 来访问图片")
    @PostMapping("upload")
    public Message upload(
            @RequestParam("file") MultipartFile file, HttpServletRequest req,String fileType
    ) throws Exception{
        String fileName = file.getOriginalFilename();
        String ext_name = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(ext_name.contains("?")){
            ext_name = ext_name.substring(0,ext_name.indexOf("?"));
        }
        long fileSize = file.getSize();
        if(fileSize > 30145728) {
            return MessageUtil.error("文件大小不能超过了3M");
        }

        String[] result = FastDFS.upload(file.getBytes(),ext_name);
        if(result!=null && result.length >1) {
            String erpGroupName = result[0];
            String erpFileName = result[1];
            BaseFile baseFile = new BaseFile();
            baseFile.setFileName(fileName);
            baseFile.setId(erpFileName);
            baseFile.setGroupName(erpGroupName);
            baseFile.setExtName(ext_name);		//后缀名
            baseFile.setFileType(fileType); 	//文件命名
            baseFile.setUploadTime(new Date().getTime());
            baseFile.setFileSize(fileSize);

            baseFileService.save(baseFile);
            //上传成功
            return MessageUtil.success("success",baseFile);
        }
        return MessageUtil.error("上传失败");
    }
}
